﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
using log4net;
using GalaSoft.MvvmLight.Messaging;

namespace KINLO.DRV.Drv
{
    public class OmronPlcDrv
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(OmronPlcDrv));
        SerialPort COM;
        string Terminator = "*\r";
        string ComId; 
        public OmronPlcDrv(string comId, int baudRate, Parity parity, int dataBits, StopBits stopBits)
        {
            ComId = comId;
            COM = new SerialPort(ComId, baudRate, parity, dataBits, stopBits);
            COM.DataReceived += COM_DataReceived;
        }
        public bool IsOpen
        {
            get { return COM.IsOpen; }
        }
        public void Open()
        {
            try
            {
                COM.Open();
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }
        public void Close()
        {
            try
            {
                COM.Close();
            }
            catch (Exception ex)
            {
                log.Error(string.Format("{0} 发生了异常 {1}", ComId, ex));
            }
        }

        /// <summary>
        /// 发送命令
        /// </summary>
        /// <param name="str"></param>
        public void Write(string str)
        {
            try
            {
                COM.Write(str);
            }
            catch (Exception ex)
            {
                log.Error(string.Format("{0} 发生了异常 {1}", ComId, ex));
            }
        }

        private void COM_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                var result = COM.ReadTo(Terminator);
                Messenger.Default.Send(result, "ReceivedPlcMsgToken");
            }
            catch (Exception ex)
            {
                log.Error(string.Format("{0} 发生了异常 {1}", ComId, ex));

            }
        }        
    }
}
